package com.abe.mvp.view.fragment;

import java.util.ArrayList;
import java.util.List;

import org.xutils.view.annotation.ViewInject;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.abe.config.Constants;
import com.abe.mvp.model.bean.exercise.ExerciseGroupBean;
import com.abe.mvp.model.bean.exercise.ExerciseNodeBean;
import com.abe.mvp.view.activity.FragmentCallbackListener.CallbackListener;
import com.abe.mvp.view.fragment.base.BaseExerciseFragment;
import com.abe.threadmill.R;
import com.abe.utils.ThreadPoolUtils;
import com.abe.view.PlaygroundView;

public class ExerciseTrailFragment extends BaseExerciseFragment {

	private CallbackListener callback;
	@ViewInject(R.id.cv)
	private PlaygroundView cv;

	private boolean is_run = false;
	private List<ExerciseNodeBean> nodeList;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		callback = (CallbackListener) getActivity();
		View view = this.onCreateView(inflater, R.layout.activity_tm_tab_trail,
				container, savedInstanceState);
		initView();
		callback.fragmentReady();
		return view;
	}

	public void initView() {
		allow_change_in_running = true;
		is_run = false;
		current_slope = 0;
		current_speed = Constants.SpeedConvertByKMH(Constants.SpeedStart);
	}

	@Override
	public void onPause() {
		super.onPause();
		cv.setRun(false);
	}

	@Override
	public void startExercise() {
		is_run = true;
		nodeList = new ArrayList<ExerciseNodeBean>();
		/** 开始运动 */
		if (!cv.isRun()) {
			ThreadPoolUtils.execute(cv);
			/** 设置速度，相应改变小球运动速率 */
			cv.setSpeed(speedConvertBallSpeed(current_speed));
			ThreadPoolUtils.execute(new TrailDJSThread());
		}
		callback.startBack();
	}

	@Override
	public void stopExercise() {
		is_run = false;
		/** 停止运动 */
		if (cv.isRun()) {
			cv.setRun(false);
		}
	}

	@Override
	public void selectPosition(int pos) {

	}

	@Override
	public void setSlope(float slope) {
		if (allow_change_in_running) {
			current_slope = slope;
		}
	}

	@Override
	public void setSpeed(float speed) {
		if (allow_change_in_running) {
			current_speed = Constants.SpeedConvertByKMH(speed);
			/** 设置速度，相应改变小球运动速率 */
			cv.setSpeed(speedConvertBallSpeed(current_speed));
		}
	}

	class TrailDJSThread implements Runnable {
		@Override
		public void run() {
			try {
				int time = 0;
				ExerciseGroupBean groupBean = new ExerciseGroupBean();
				/** 未主动停止锻炼 */
				while (is_run) {
					/** 时间间隔1秒即重新计算累加 */
					Thread.sleep(1000);
					time++;
					/** 判断速度是否改变，改变记录时间节点 */
					if (current_speed != old_speed
							|| current_slope != old_slope) {
						nodeList.add(new ExerciseNodeBean(time, old_speed,
								old_slope));
						old_speed = current_speed;
						old_slope = current_slope;
					}
					/** 计算累计 */
					groupBean = getCumulativeData(time);
					/** 通知刷新 */
					callback.updateExercise(groupBean);
				}
				callback.stopBack(is_run,groupBean);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	private ExerciseGroupBean getCumulativeData(int time) {
		ExerciseGroupBean groupBean = new ExerciseGroupBean();
		groupBean.setMaxNum(0);
		/** 获取小球累计运行长度，转换为累计跑步距离 */
		float distance = (cv.getAllDis() * lengthConvertPX());
		float calorie = Constants.getKcal(distance);
		groupBean.setDistance(distance);
		groupBean.setKeepTime(time);
		groupBean.setCalorie(calorie);
		if (nodeList.size() == 0) {
			distance = (current_speed * time);
			groupBean.setAverageSlope(current_slope);
			groupBean.setAverageSpeed(current_speed);
		} else {
			float slopes = 0;
			ExerciseNodeBean bean = nodeList.get(0);
			int old_time = bean.getNodeTime();
			int current_time = old_time;
			distance = (bean.getNodeTime() * bean.getNodeSpeed());
			slopes = (bean.getNodeTime() * bean.getNodeSlope());
			for (int i = 1; i < nodeList.size(); i++) {
				bean = nodeList.get(i);
				current_time = bean.getNodeTime();
				distance = (distance + bean.getNodeSpeed()
						* (current_time - old_time));
				slopes = (slopes + bean.getNodeSlope()
						* (current_time - old_time));
				old_time = current_time;
			}
			groupBean.setAverageSlope(slopes / time);
			groupBean.setAverageSpeed(distance / time);
		}
		return groupBean;
	}

	/**
	 * 跑步机速度转化为小球速度
	 * 
	 * @param speed
	 *            跑步机速度，单位m/s
	 * @return ballSpeed px/s
	 * */
	private float speedConvertBallSpeed(float speed) {
		float ballSpeed = speed / lengthConvertPX();
		return ballSpeed/10f;
	}

	/** 跑道长度与像素相互转换:1px对应真实米数 */
	private float lengthConvertPX() {
		/** 直行跑道长度 */
		float ballRunWayLength = cv.getBallRunWayLength();
		/** 弧形跑道半径 */
		float ballRunWayRadius = cv.getBallRunWayRadius();
		/** 获取小球所在轨道的像素长度 */
		float allLength = (float) (ballRunWayLength * 2 + ballRunWayRadius
				* Math.PI * 2);
		/** 跑道长度 400 */
		return 400 / allLength;
	}

	@Override
	public boolean checkInitComplete() {
		isCanStart = true;
		return isCanStart;
	}

	@Override
	public boolean checkIsCanSetSpeedSlope() {
		return true;
	}

}
